package cn.jjxx.shiro.session.factory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionContext;
import org.apache.shiro.web.session.mgt.WebSessionContext;
import org.framework.superutil.thirdparty.http.CookieUtils;

import cn.jjxx.core.utils.IpUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.shiro.session.ShiroSession;
import cn.jjxx.shiro.session.config.RedisUtil;
import cn.jjxx.shiro.session.core.ShiroSessionRedisConstant;

/**
 * shiro使用SessionFactory创建session,这里我们自定义SessionFactory，让它创建我们自定义的Session.
 *@Title ShiroSessionFactory.java
 *@description TODO
 *@time 2020年7月16日 下午12:20:37
 *@author YAOXIONG
 *@version 1.0
 *
 */
public class ShiroSessionFactory implements SessionFactory {
	@Override
	public Session createSession(SessionContext initData) {
		ShiroSession session = new ShiroSession();
		HttpServletRequest request = (HttpServletRequest)initData.get(DefaultWebSessionContext.class.getName() + ".SERVLET_REQUEST");
		session.setHost(getIpAddress(request));
		 

		return session;
	}

	public static String getIpAddress(HttpServletRequest request) {
		String localIP = "127.0.0.1";
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}


